package com.turing.data.service.element.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.turing.common.entity.Context;
import com.turing.common.response.CommonCode;
import com.turing.common.response.PageBean;
import com.turing.common.util.AssertUtil;
import com.turing.common.util.CollectionUtil;
import com.turing.common.util.StringUtils;
import com.turing.common.util.Tools;
import com.turing.data.dao.element.TemplateMapper;
import com.turing.data.model.domain.element.SubProduct;
import com.turing.data.model.domain.element.Template;
import com.turing.data.service.element.SubProductService;
import com.turing.data.service.element.TemplateService;
import com.turing.data.vo.in.element.TemplateSearchVO;
import com.turing.data.vo.in.element.TemplateVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class TemplateServiceImpl extends ServiceImpl<TemplateMapper, Template> implements TemplateService {

    @Autowired
    private TemplateMapper templateMapper;

    @Autowired
    private SubProductService subProductService;

    @Override
    public String getTemplateNameById(String templateSn) {
        Template template = new LambdaQueryChainWrapper<>(templateMapper)
                .eq(Template::getTemplateSn, templateSn)
                .eq(Template::getIsDel, 0)
                .last("limit 1")
                .one();
        return Optional.ofNullable(template).map(Template::getTemplateName).orElse("");
    }

    @Override
    public Template getTemplateById(String templateSn) {
        return new LambdaQueryChainWrapper<>(templateMapper)
                .eq(Template::getTemplateSn, templateSn)
                .eq(Template::getIsDel, 0)
                .last("limit 1")
                .one();
    }

    @Override
    public Template getTemplateByName(String templateName) {
        return new LambdaQueryChainWrapper<>(templateMapper)
                .eq(Template::getTemplateName, templateName)
                .eq(Template::getIsDel, 0)
                .last("limit 1")
                .one();
    }

    @Override
    public Set<String> getProductTemplate() {
        QueryWrapper<Template> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type","11");
        //获取所有子场景id
        List<Template> templates = templateMapper.selectList(queryWrapper);
        Set<String> templateIdSet = templates.stream().map(Template :: getTemplateSn).collect(Collectors.toSet());
        templateIdSet.add("11");
        return templateIdSet;
    }

    @Override public Boolean checkTemplatePrivileges(String templateId){
        Set<String> privilegeSet = new HashSet<>(Context.getTokenContext().getTemplates().keySet());
        Template template = templateMapper.selectById(templateId);
        //校验权限
        return privilegeSet.contains(template.getTemplateSn()) || ("11".equals(template.getType()) && privilegeSet.contains(template.getType()));
    }

    @Override public Set<String> getPrivilegeTemplate(){
        //获取权限
        Set<String> privilegeSet = Context.getTokenContext().getTemplates().keySet();
        if (privilegeSet.contains("11")) {
            privilegeSet.addAll(getProductTemplate());
        }
        return privilegeSet;
    }

    @Override public boolean optionAutoAudit(Integer autoAudit,String templateSn){
        //验证权限
        Template template = templateMapper.selectById(templateSn);
        //权限控制是否可以开启自动审核
        if ("11".equals(template.getType())) {
            AssertUtil.isTrue(!template.getCreatedBy().equals(Context.getTokenContext().getUserCode()), CommonCode.NOT_AUTHORIZATION);
        } else {
            AssertUtil.isTrue(Context.getTokenContext().getRoleId() != 26,CommonCode.NOT_AUTHORIZATION);
        }

        //开启/关闭自动审核
        template = Template.builder().autoAudit(autoAudit).templateSn(templateSn).updatedTime(new Date())
                .createdBy(Context.getTokenContext().getUserCode()).build();
        return templateMapper.updateById(template) > 0;
    }

    @Override
    public boolean needsJSON(String templateSn) {

        Template template = lambdaQuery().eq(Template::getTemplateSn, templateSn).select(Template::getNeedsJson).one();
        return Optional.ofNullable(template).map(t->t.getNeedsJson() == 1).orElse(false);

    }

    @Override
    public PageBean<TemplateVo> queryByCondition(TemplateSearchVO templateSearchVO) {

        Integer pageIndex = templateSearchVO.getPageIndex();
        Integer pageSize = templateSearchVO.getPageSize();
        PageHelper.startPage(templateSearchVO.getPageIndex(),templateSearchVO.getPageSize());
        LambdaQueryWrapper<Template> queryWrapper = new LambdaQueryWrapper<>();
        Optional.ofNullable(templateSearchVO.getSearchText()).filter(StringUtils::isNotEmpty).ifPresent(t->queryWrapper.like(Template::getTemplateName,t));
        Optional.ofNullable(templateSearchVO.getIndustry()).filter(StringUtils::isNotEmpty).ifPresent(t->queryWrapper.eq(Template::getIndustry,t));
        Optional.ofNullable(templateSearchVO.getType()).filter(StringUtils::isNotEmpty).ifPresent(t->queryWrapper.eq(Template::getType,t));
        Map<String, Integer> privileges = Context.getTokenContext().getTemplates();
        Optional.ofNullable(privileges).filter(Tools::isNotEmpty).ifPresent(p->queryWrapper.in(Template::getTemplateSn,privileges.keySet()));
        List<Template> templates = list(queryWrapper);
        if(Tools.isNotEmpty(templates) && Tools.isNotEmpty(privileges)){
            List<TemplateVo> templateVos = templates.stream().map(t -> {
                TemplateVo templateVo = new TemplateVo();
                BeanUtils.copyProperties(t, templateVo);
                return templateVo;
            }).collect(Collectors.toList());
            int count = count(queryWrapper);
            PageBean<TemplateVo> pageBean = new PageBean<TemplateVo>(pageIndex, pageSize, count);
            pageBean.setItems(templateVos);
            return pageBean;
        }
        return new PageBean<>();

    }

    @Override
    public List<SubProduct> getSubProducts(String templateId ) {

        return subProductService.lambdaQuery().eq(SubProduct::getTemplateId,templateId).list();

    }

    @Override
    public Boolean CVOnline() {

        return lambdaQuery().like(Template::getTemplateName,"简历").eq(Template::getPublished,1).count() > 0;

    }


}
